# -*- coding: utf-8 -*-
import logging
from logging import handlers
import colorlog
import time
import os


def ensure_path_sep(path):
    return path.replace('\\', '/')


class LogHandler:
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }

    def __init__(
            self,
            level='info',
            when='D',
            fmt="%(levelname)-8s%(asctime)s%(name)s:%(filename)s:%(lineno)d %(message)s"
    ):
        # Ensure the 'logs' directory exists
        log_directory = ensure_path_sep('logs')
        os.makedirs(log_directory, exist_ok=True)

        # Create subdirectories for different log levels
        level_directory = ensure_path_sep(f"{log_directory}/{level}")
        os.makedirs(level_directory, exist_ok=True)

        self.logger = logging.getLogger(level)
        formatter = self.log_color()
        format_str = logging.Formatter(fmt)
        self.logger.setLevel(self.level_relations.get(level))

        # Using absolute path
        log_file = os.path.abspath(f"{level_directory}/{level}-{now_time_day}.log")

        screen_output = logging.StreamHandler()
        screen_output.setFormatter(formatter)

        time_rotating = handlers.TimedRotatingFileHandler(
            filename=log_file,
            when=when,
            backupCount=3,
            encoding='utf-8'
        )
        time_rotating.setFormatter(format_str)

        self.logger.addHandler(screen_output)
        self.logger.addHandler(time_rotating)

    @classmethod
    def log_color(cls):
        log_colors_config = {
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'red',
        }

        formatter = colorlog.ColoredFormatter(
            '%(log_color)s[%(asctime)s] [%(name)s] [%(levelname)s]: %(message)s',
            log_colors=log_colors_config
        )
        return formatter


now_time_day = time.strftime("%Y-%m-%d", time.localtime())
INFO = LogHandler(level='info')
ERROR = LogHandler(level='error')
WARNING = LogHandler(level='warning')

if __name__ == '__main__':
    ERROR.logger.error("666666")
    INFO.logger.info("Some info message")
    WARNING.logger.warning("Some warning message")

    print(now_time_day)
